package com.xncoding.freemarker.ctr;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.CaseFormat;
import com.xncoding.freemarker.model.*;
import com.xncoding.freemarker.service.GenerateCodeService;
import com.xncoding.freemarker.utile.RegexUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class GenerateCodeController {
    @Autowired
    GenerateCodeService generateCodeService;


    @PostMapping("/generateCode")
    public RespBean generateCode(@RequestBody List<TableClass> tableClassList, HttpServletRequest req) {
        return generateCodeService.generateCode(tableClassList, req.getServletContext().getRealPath("/"));
    }

    @PostMapping("/generateCode01")
    public RespBean generateCode01(@RequestBody String body, HttpServletRequest req) {

        List<TableClass> tableClassList = new ArrayList<>();
        TableClass tableClass = new TableClass();
        tableClass.setPackageName("com.xjrccb.bizplat.ebank.impl.asl");
        tableClass.setEosPath("com.xjrccb.bizplat.ebank.impl.asl");
        String table_name = "eptOperCmnQry";
        String modelName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, table_name);
        String businessName = "Index";
        tableClass.setTableName(table_name);
        tableClass.setModelName(modelName);
        tableClass.setBusinessName(businessName);
        tableClass.setEosModelName(businessName);
        tableClass.setTableRemark("备注");

        ColumnClass cls = new ColumnClass();
        cls.setPropertyName("etpId");
        cls.setColumnName("etpId");
        cls.setType("VARCHAR");
        cls.setRemark("网银客户号");
        cls.setPrimary(false);

        ColumnClass cls1 = new ColumnClass();
        cls1.setPropertyName("coreCusNo");
        cls1.setColumnName("coreCusNo");
        cls1.setType("VARCHAR");
        cls1.setRemark("核心客户号");
        cls1.setPrimary(false);

        ColumnClass cls2 = new ColumnClass();
        cls2.setPropertyName("menuId");
        cls2.setColumnName("menuId");
        cls2.setType("VARCHAR");
        cls2.setRemark("菜单ID");
        cls2.setPrimary(false);

        ColumnClass cls3 = new ColumnClass();
        cls3.setPropertyName("menuName");
        cls3.setColumnName("menuName");
        cls3.setType("VARCHAR");
        cls3.setRemark("菜单名称");
        cls3.setPrimary(false);

        ColumnClass cls4 = new ColumnClass();
        cls4.setPropertyName("chnlTyp");
        cls4.setColumnName("chnlTyp");
        cls4.setType("VARCHAR");
        cls4.setRemark("渠道类型");
        cls4.setPrimary(false);

        List<ColumnClass> columns =new ArrayList<>();
        columns.add(cls);
        columns.add(cls1);
        columns.add(cls2);
        columns.add(cls3);
        columns.add(cls4);

        tableClass.setColumns(columns);

        tableClassList.add(tableClass);
//        return body;
        return generateCodeService.generateCode(tableClassList, req.getServletContext().getRealPath("/"));
    }

    @PostMapping("/mbankgenerateCode")
    public RespBean MbankgenerateCode(HttpServletRequest req) {

        List<mbank> classList = new ArrayList<>();
        mbank m = new mbank();
        m.setBusinessName("myAccount");
        m.setBusinessNameNotes("我的账户");
        m.setPackageName("com.xjrccb.bizplat.mbank.impl.asl");

        /**
                                                                     还款信息详情查询 网贷	/bcacc/bcaccp/FsAccOnlnLoan/LoanRpyDtlQry
                                                                     还款信息列表查询 网贷	/bcacc/bcaccp/FsAccOnlnLoan/LoanRpyListQry
                                                                     结清证明申请	/bcprd/bcprds/FsPrdInteLoanMgr/LoanClraCerAppl
                                                                     结清证明下载	/bcprd/bcprds/FsPrdInteLoanMgr/LoanClraCerDnld
         */

        controllerModel c1 = new controllerModel("LoanRpyDtlQry","还款信息详情查询 网贷","/bcacc/bcaccp/FsAccOnlnLoan/LoanRpyDtlQry");
        controllerModel c2 = new controllerModel("LoanRpyListQry","还款信息列表查询 网贷","/bcacc/bcaccp/FsAccOnlnLoan/LoanRpyListQry");
        controllerModel c3 = new controllerModel("LoanClraCerAppl","结清证明申请","/bcprd/bcprds/FsPrdInteLoanMgr/LoanClraCerAppl");
        controllerModel c4 = new controllerModel("LoanClraCerDnld","结清证明下载","/bcprd/bcprds/FsPrdInteLoanMgr/LoanClraCerDnld");

        List<controllerModel> list = new ArrayList<>();
        list.add(c1);
        list.add(c2);
        list.add(c3);
        list.add(c4);

        m.setColumns(list);

        classList.add(m);

        return generateCodeService.mbankGenerateCode(classList, req.getServletContext().getRealPath("/"));
    }


    /**
     * 主页
     *
     * @param model
     * @return
     */
    @RequestMapping({"/", "/index"})
    public ModelAndView index(ModelAndView model) {
        model.setViewName("file");
        return model;
    }


    /**
     * 导入
     */
    @PostMapping("import")
    public RespBean ordergeneratexml(MultipartFile file,HttpServletRequest req) throws Exception {
        //根据file得到Workbook,主要是要根据这个对象获取,传过来的excel有几个sheet页
        Workbook hssfWorkbook = getWorkBook(file);
        //获取sheet数量
        int sheetNum = hssfWorkbook.getNumberOfSheets();
        ImportParams params = new ImportParams();
        //表头在第几行
        params.setTitleRows(10);
        //是否需要通过key-value导入方法，获取特定字段
        params.setReadSingleCell(true);
        //判断一个cell是key的规则,可以自定义,默认就是 “:”
        params.setKeyMark(":");

        List<mock> mCtrList = new ArrayList<>();
        mock moc = new mock();
        moc.setBusinessName("qwee");
        moc.setBusinessNameNotes("dsfdsfdsefefe");

        List<mockCtr> mockCtrList = new ArrayList<>();
        mockCtr mocc;
        ColumnClass col ;
        for (int sheetIndex = 0; sheetIndex < sheetNum; sheetIndex++) {
            //第几个sheet页
            params.setStartSheetIndex(sheetIndex);
            //获取表头下的数据
//            ExcelImportResult<Map> result = ExcelImportUtil.importExcelMore(new File("D:\\Desktop\\1.xlsx"),
//                    Map.class, params);
            //获取表头下的数据
            ExcelImportResult<Map> result = ExcelImportUtil.importExcelMore(file.getInputStream(), Map.class, params);
            List<Map> list = result.getList();
            //获取特定字段的map
            Map<String, Object> map = result.getMap();
            System.out.println(JSON.toJSONString(list));
            System.out.println(JSON.toJSONString(map));
            System.out.println("----------------");

            List<ColumnClass> listColin = new ArrayList<>();
//            List<ColumnClass> listColout = new ArrayList<>();
            mocc = new mockCtr();

            mocc.setModelName(map.get("服务方法:").toString());
            mocc.setEosPath(map.get("服务路径:").toString());
            mocc.setModelNameNotes(map.get("服务名称:").toString());

            for (Map mapMock : list){
                if(!mapMock.containsKey("字段名称")|| null == mapMock.get("字段名称") || "字段名称".equals(mapMock.get("字段名称").toString())){
                    continue;
                }
                col = new ColumnClass();
                col.setPropertyName(getCOL("字段名称",mapMock));
                col.setType(getCOL("类型",mapMock));
                col.setPropertyNotes(getCOL("中文含义",mapMock));
                col.setRemark(getCOL("数据项说明",mapMock));
                col.setSfNoll(getCOL("是否必输",mapMock).equals("是")?true:false||getCOL("是否必输",mapMock).equals("Y")?true:false);
                listColin.add(col);
            }
            mocc.setColumns(listColin);
            mockCtrList.add(mocc);

        }
        moc.setMockcolumns(mockCtrList);
        mCtrList.add(moc);
        return generateCodeService.mockGenerateCode(mCtrList, req.getServletContext().getRealPath("/"));
    }

    public static String getCOL(String key,Map map){
        if(null != map.get(key) && !"".equals(map.get(key))){
            return map.get(key).toString().trim();
        }
        return "";
    }

    public static Workbook getWorkBook(MultipartFile file) throws IOException {
        //这样写excel能兼容03和07
        InputStream is = file.getInputStream();
        Workbook hssfWorkbook = null;
        try {
            hssfWorkbook = new HSSFWorkbook(is);
        } catch (Exception ex) {
            is =file.getInputStream();
            hssfWorkbook = new XSSFWorkbook(is);
        }
        return hssfWorkbook;
    }


}


